/*
 * Copyright 2003,2004 The Apache Software Foundation
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package eu.jakubiak.jpa.translator.provider;

import eu.jakubiak.jpa.translator.TranslationKey;
import eu.jakubiak.jpa.translator.TranslatorProperties;
import eu.jakubiak.jpa.translator.provider.entities.Translation;
import eu.jakubiak.jpa.translator.provider.entities.TranslationId;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

/**
 *
 * @author Antek
 */
public class JpaProvider implements Provider {

    private static EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory(TranslatorProperties.getPersistenceUnitName());
    
    // TODO trzeba się zastanowić czy to coś nie powinno być statyczne
    private EntityManager entityManager = null; 
    

    
    
    public String get(TranslationKey key) {
        // TODO trzeba sie zastanowic jak obslugiwac wyjatki
        entityManager = entityManagerFactory.createEntityManager();
        Translation translation = entityManager.find(Translation.class, new TranslationId(key));
        entityManager.close();
        if(translation!=null) {
            return translation.getTranslatedSerializedValue();
        } else {
            return null;
        }
    }

    
    public void set(TranslationKey key, String value) {
        // TODO trzeba sie zastanowic jak obslugiwac wyjatki
        entityManager = entityManagerFactory.createEntityManager();
        entityManager.getTransaction().begin();
        Translation translation = entityManager.find(Translation.class, new TranslationId(key));
        if (translation != null) {
            translation.setTranslatedSerializedValue(value);
        } else {
            translation = new Translation(key,value);
            entityManager.persist(translation);
        }
        entityManager.getTransaction().commit();
        entityManager.close();
    }
}
